package homework.test;

//Objects.hash(...);方法需要导包

import java.util.Objects;

public class RewriteEqualsAndHashCode {
    private String name;
    private int age;

    public RewriteEqualsAndHashCode(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {

        //如果对象为空则返回false
        if (obj == null) {
            return false;
        }

        //如果两个对象地址相同则返回true
        if (this == obj) {
            return true;
        }

        //如果两个对象类型不相同则返回false
        if (getClass() != obj.getClass()) {
            return true;
        }

        //最后强制类型转换为该类对象，再比较字段值
        RewriteEqualsAndHashCode another = (RewriteEqualsAndHashCode) obj;
        //字符串比较用equals而不是==
        return (name.equals(another.name)) && (age == another.age);

    }

    @Override
    public int hashCode() {

        // 为了与 equals 保持一致，可以在 hashCode 方法中根据 equals 方法中所比较的字段来产生哈希码值
        return Objects.hash(name, age);

    }

    public static void main(String[] args) {

        RewriteEqualsAndHashCode example1 = new RewriteEqualsAndHashCode("星宿1", 30000);
        RewriteEqualsAndHashCode example2 = new RewriteEqualsAndHashCode("星宿1", 30000);

        System.out.println("example1 和 example2 相等吗？");
        System.out.println(example1.equals(example2));

        System.out.println("example1的哈希码值：" + example1.hashCode());
        System.out.println("example2的哈希码值：" + example2.hashCode());


    }

}
